$(document).ready(function() {
    reloadTree();
    loadRoomTable();
    $('#reset').click();
    layui.use('form', function() {
        var form = layui.form;

        //监听提交
        form.on('submit(formDemo)', function(data) {
           let params = new FormData();

            params.append('name', data.field.name);
            params.append('type', data.field.type);
            params.append('chargePerson', data.field.person);
            params.append('chargeNumber', data.field.phone);
            params.append('longitude', data.field.longitude);
            params.append('latitude', data.field.latitude);
            params.append('address', data.field.address);
            params.append('rackNumber', data.field.racknum);
            addRoom(params)
            return false;
        });
    });

    /*日历插件*/
    layui.use('laydate', function() {
        var laydate = layui.laydate;
        //执行一个laydate实例
        laydate.render({
            elem: '#date-input',
            range: true,

        });
    });
})

var areaCode = '';
var isPar = true;
var operate;
var orgid = '';
let prarms = {};
//机房表格
function loadRoomTable() {
    if (prarms) {
        name = prarms.name;
        areaName = prarms.areaName;
        startTime = prarms.startTime;
        endTime = prarms.endTime;
    } else {
        var name = '';
        var areaName = '';
        var startTime = '';
        var endTime = '';
    }
    layui.use('table', function() {
        var table = layui.table;

        //第一个实例
        table.render({
            title: '',
            text: {
                none: '暂无数据'
            },
            elem: '#body-content-table',
            skin: 'nob',
            url: ajaxPrefix() + '/manage/room/list',
            headers: { SessionId: localStorage.getItem('sessionId') },
            where: {
                pageSize: 10,
                areaCode:areaCode,
                name:name,
                areaName:areaName,
                startTime:startTime,
                endTime:endTime
            },
            parseData: function(res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            },
            request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                    ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            page: {
                limit: 10,
            } //开启分页
            ,
            cols: [
                [ //表头
                    {
                        field: 'name',
                        title: '机房名称',
                        align: 'center'
                    },{
                        field: 'type',
                        title: '类型',
                        templet: function(d) {
                            var type;
                            if(d.type == 1){
                                type = '机房';
                            } else if(d.type == 2){
                                type = '管井';
                            }
                            return type;
                        },
                        align: 'center'
                    }, {
                        field: 'chargeNumber',
                        title: '机房负责人电话',
                        align: 'center',
                    }, {
                        field: 'orgName',
                        title: '所属组织',
                        align: 'center'
                    }, {
                        field: 'areaName',
                        title: '所属街道',
                        align: 'center',
                    }, {
                        field: 'dataTime',
                        title: '创建时间',
                        templet: function(d) {
                            return d.dataTime == undefined ? '暂无' : d.dataTime.substring(0, 19)
                        },
                        align: 'center'
                    }, {
                        title: '操作',
                        align: 'center',
                        width: 120,
                        templet: function(d) {
                            let res = JSON.stringify(d);
                            return `<div>
                                        <div class="table-tool">
                                            <div onclick=initUpdate('${d.id}','${d.name}','${d.type}','${d.chargePerson}','${d.chargeNumber}','${d.longitude}','${d.latitude}','${d.address}','${d.orgName}','${d.rackNumber}')><button>修改</button></div>
                                            <div onclick=del('${d.id}')><button>删除</button></div>
                                        </div>
                                   </div>`;

                        },
                    },
                ]
            ]
        });
    });
}

function initUpdate(id,name,type,chargePerson,chargeNumber,
    longitude,latitude,address,orgName,rackNumber) {
            operate = id;
            $('.add-room>.main-tit>label').html('修改');
            $("#name").val(name);
            $("#room-type").val(type);
            renderForm();
            $("#person").val(chargePerson);
            $("#phone").val(chargeNumber);
            $("#map-input").val(longitude + ','+latitude);
            $("#longitude").val(longitude);
            $("#latitude").val(latitude);
            $("#address").val(address);
            $("#racknum").val(rackNumber);
            $("#org").val(orgName);
            $('.add-room').show();
}

function del(id) {
    layer.confirm('确定删除该机房吗?', {
        btn: ['确定', '取消']
    }, function(isConfirm) {
        $.ajax({
        url: ajaxPrefix() + '/manage/room/delete?id='+id,
        type: 'get',
        contentType: "application/json",
        beforeSend: function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
        },
        success: function(result) {
            if (result.status == 200) {
                layer.msg("删除成功");
                loadRoomTable();
            } else {
                layer.msg('请先删除机房下设备！', { icon: 7 });
            }

        }
    });
    });
}

$('.layui-atn').click(function() {
    prarms.name = $('#computername').val();
    prarms.areaName = $('#areaname').val();
    let date = $('#date-input').val();
    prarms.startTime = date.substring(0, 10);
    prarms.endTime = date.substring(13, 23);
    loadRoomTable(prarms);
})

/*树*/
var setting = {
    async: {
        autoParam: ["id"],
        enable: true,
        url: getAsyncUrl,
        type: "get",
        dataFilter: ajaxDataFilter,
        headers: { "SessionId": localStorage.getItem('sessionId') },
    },
    view: {
        expandSpeed: "fast",
        fontCss: getFont,
        showLine: true,
        dblClickExpand: false,
        showIcon: false
    },
    callback: {
        onAsyncSuccess: zTreeOnAsyncSuccess,
        onClick: zTreeOnClick,
        beforeExpand: beforeExpand,
        onExpand: onExpand
    },
    data: {
        key: {
            title: "name"
        },
        simpleData: {
            enable: true,
            idKey: "code",
            pIdKey: "parentCode"
        }
    }
};

/*树*/
var settingd = {
    async: {
        autoParam: ["id"],
        enable: true,
        url: getAsyncUrld,
        type: "post",
        dataFilter: ajaxDataFilterd,
        headers: { "SessionId": localStorage.getItem('sessionId') },
    },
    view: {
        expandSpeed: "fast",
        fontCss: getFontd,
        showLine: true,
        dblClickExpand: false,
        showIcon: false
    },
    callback: {
        onAsyncSuccess: zTreeOnAsyncSuccessd,
        onClick: zTreeOnClickd,
        beforeExpand: beforeExpandd,
        onExpand: onExpandd
    },
    data: {
        key: {
            title: "name"
        },
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId"
        }
    }
};

var zNodes;

function reloadTree() {
    zTree = $.fn.zTree.init($("#treeDemo"), setting);
}

function reloadTreed() {
    zTree = $.fn.zTree.init($("#treeDemod"), settingd);
}

function getAsyncUrl(treeId, treeNode) {
    if (!treeNode) {
        url = ajaxPrefix() + "/area/tree?areaCode=" + 320113;
    } else {
        url = ajaxPrefix() + "/area/roomtree?areaCode=" + treeNode.id;
    }

    return url;
}

function getAsyncUrld(treeId, treeNode) {
    if (!treeNode) {
        url = ajaxPrefix() + "/manage/org/tree_root";
    } else {
        url = ajaxPrefix() + "/manage/org/tree_node";
    }

    return url;
}

//异步数据过滤
function ajaxDataFilter(treeId, parentNode, childNodes) {

    return childNodes;
}

//异步数据过滤
function ajaxDataFilterd(treeId, parentNode, childNodes) {

    return childNodes;
}

var _selTreeId = null;
//异步加载成功
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
    if (!treeNode) { //根节点
        var rootNode = zTree.getNodesByParam("level", 0)[0];
        return;
    }

    var selTreeId = _selTreeId;
    if (!!selTreeId) {
        var selNode = zTree.getNodeByParam("id", selTreeId);
        if (!!selNode) {
            _selTreeId = null;
            zTree.selectNode(selNode);
            zTreeOnClick();
        }
    }
}

var _selTreeIdd = null;
//异步加载成功
function zTreeOnAsyncSuccessd(event, treeId, treeNode, msg) {
    if (!treeNode) { //根节点
        var rootNode = zTree.getNodesByParam("level", 0)[0];
        return;
    }

    var selTreeId = _selTreeIdd;
    if (!!selTreeId) {
        var selNode = zTree.getNodeByParam("id", selTreeId);
        if (!!selNode) {
            _selTreeIdd = null;
            zTree.selectNode(selNode);
            zTreeOnClickd();
        }
    }
}

//右击事件
function getFont(treeId, node) {
    return node.font ? node.font : {};
}

//右击事件
function getFontd(treeId, node) {
    return node.font ? node.font : {};
}


//仅能打开一个子节点
var curExpandNode = null;

function beforeExpand(treeId, treeNode) {
    var pNode = curExpandNode ? curExpandNode.getParentNode() : null;
    var treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
    for (var i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
        if (treeNode !== treeNodeP.children[i]) {
            zTree.expandNode(treeNodeP.children[i], false);
        }
    }
    while (pNode) {
        if (pNode === treeNode) {
            break;
        }
        pNode = pNode.getParentNode();
    }
    if (!pNode) {
        singlePath(treeNode);
    }

}

//仅能打开一个子节点
var curExpandNoded = null;

function beforeExpandd(treeId, treeNode) {
    var pNode = curExpandNoded ? curExpandNoded.getParentNode() : null;
    var treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
    for (var i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
        if (treeNode !== treeNodeP.children[i]) {
            zTree.expandNode(treeNodeP.children[i], false);
        }
    }
    while (pNode) {
        if (pNode === treeNode) {
            break;
        }
        pNode = pNode.getParentNode();
    }
    if (!pNode) {
        singlePathd(treeNode);
    }

}

function singlePath(newNode) {
    if (newNode === curExpandNode) return;
    if (curExpandNode && curExpandNode.open == true) {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        if (newNode.parentTId === curExpandNode.parentTId) {
            zTree.expandNode(curExpandNode, false);
        } else {
            var newParents = [];
            while (newNode) {
                newNode = newNode.getParentNode();
                if (newNode === curExpandNode) {
                    newParents = null;
                    break;
                } else if (newNode) {
                    newParents.push(newNode);
                }
            }
            if (newParents != null) {
                var oldNode = curExpandNode;
                var oldParents = [];
                while (oldNode) {
                    oldNode = oldNode.getParentNode();
                    if (oldNode) {
                        oldParents.push(oldNode);
                    }
                }
                if (newParents.length > 0) {
                    zTree.expandNode(oldParents[Math.abs(oldParents.length - newParents.length) - 1], false);
                } else {
                    zTree.expandNode(oldParents[oldParents.length - 1], false);
                }
            }
        }
    }
    curExpandNode = newNode;
}

function singlePathd(newNode) {
    if (newNode === curExpandNoded) return;
    if (curExpandNoded && curExpandNoded.open == true) {
        var zTree = $.fn.zTree.getZTreeObj("treeDemod");
        if (newNode.parentTId === curExpandNode.parentTId) {
            zTree.expandNode(curExpandNoded, false);
        } else {
            var newParents = [];
            while (newNode) {
                newNode = newNode.getParentNode();
                if (newNode === curExpandNoded) {
                    newParents = null;
                    break;
                } else if (newNode) {
                    newParents.push(newNode);
                }
            }
            if (newParents != null) {
                var oldNode = curExpandNoded;
                var oldParents = [];
                while (oldNode) {
                    oldNode = oldNode.getParentNode();
                    if (oldNode) {
                        oldParents.push(oldNode);
                    }
                }
                if (newParents.length > 0) {
                    zTree.expandNode(oldParents[Math.abs(oldParents.length - newParents.length) - 1], false);
                } else {
                    zTree.expandNode(oldParents[oldParents.length - 1], false);
                }
            }
        }
    }
    curExpandNoded = newNode;
}

function onExpand(event, treeId, treeNode) {
    curExpandNode = treeNode;
}

function onExpandd(event, treeId, treeNode) {
    curExpandNoded = treeNode;
}

//单击树节点事件
function zTreeOnClick(event, treeId, treeNode) {
    isPar = treeNode.isParent;
    areaCode = treeNode.code;
    loadRoomTable();
}

//单击树节点事件
function zTreeOnClickd(event, treeId, treeNode) {
    orgid = treeNode.id;
    $('#org').val(treeNode.name);
    $('.main-left-treee').hide();
}

$('#org').click(function() {
        reloadTreed();
        $('.main-left-treee').toggle();
});


$('.layui-btn').click(function() {
    if (isPar) {
        layer.msg('请先在右侧选择所属街道')
    } else {
        operate = true;
        $('.add-room>.main-tit>label').html('新增');
        $('.add-room').show();
    }

})
$(".add-room>.main-tit>div").click(function() {
    $('.add-room').hide();
    $('#reset').click();
    orgid='';
    $('.map-box').hide();
    $('.add-room-body').show();
    map && map.destroy();
})
/*新增机房*/
addRoom = (params) => {
if (operate === true) {
    if(orgid==''){
        layer.msg('请先选择组织！', { icon: 7 });
        return;
    }
     params.append('areaCode', areaCode);
     params.append('orgid', orgid);
    $.ajax({
        url: ajaxPrefix() + '/manage/room/add',
        type: 'post',
        data: params,
        dataType: "json",
        beforeSend: function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
        },
        cache: false,
        processData: false,
        contentType: false,
        success: function(res) {
            if (res.status == 200) {
                layer.msg('新增成功', { time: 1000 });
                $(".add-room>.main-tit>div").click();
                loadRoomTable();
            } else {
                layer.msg('操作失败！', { time: 1000 })
            }

        }
    });
   } else {
        params.append('id', operate);
        params.append('orgid', orgid);
        $.ajax({
        url: ajaxPrefix() + '/manage/room/update',
        type: 'post',
        data: params,
        dataType: "json",
        beforeSend: function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
        },
        cache: false,
        processData: false,
        contentType: false,
        success: function(res) {
            if (res.status == 200) {
                layer.msg('修改成功', { time: 1000 });
                $(".add-room>.main-tit>div").click();
                loadRoomTable();
            } else {
                layer.msg('操作失败！', { time: 1000 })
            }
        }
    });
   }
}

var map;
/*地图*/
$('#map-input').click(function() {
    $('.add-room-body').hide();
    $('.map-box').show();
    map = new AMap.Map('map', {
        zoom: 13,
        center: [121.404195, 31.186536],
        mapStyle: 'amap://styles/6f2ac55a0fce7bb44145e64373f74f99',

    });
    map.on('click', function(e) {
        $('.add-room-body').show();
        $('.map-box').hide();
        $('#map-input').val(e.lnglat.getLng() + ',' + e.lnglat.getLat());
        $('input[name=longitude]').val(e.lnglat.getLng());
        $('input[name=latitude]').val(e.lnglat.getLat());
    });
    AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {

        var poiPicker = new PoiPicker({
            input: 'pickerInput'
        });

        //初始化poiPicker
        poiPickerReady(poiPicker);
    });

    function poiPickerReady(poiPicker) {

        window.poiPicker = poiPicker;

        var marker = new AMap.Marker();

        var infoWindow = new AMap.InfoWindow({
            offset: new AMap.Pixel(0, -20)
        });
        marker.on('click', function(e) {
            $('.add-room-body').show();
            $('.map-box').hide();
            $('#map-input').val(e.lnglat.getLng() + ',' + e.lnglat.getLat());
            $('input[name=longitude]').val(e.lnglat.getLng());
            $('input[name=latitude]').val(e.lnglat.getLat());
        });
        //选取了某个POI
        poiPicker.on('poiPicked', function(poiResult) {

            var poi = poiResult.item;

            marker.setMap(map);

            marker.setPosition(poi.location);


            map.setFitView();
        });

    }
})
